#import "MobAdBannerPlatformView.h"
#import <BUAdSDK/BUAdSDK.h>
#import "KawaAdPlugin.h"

#pragma mark - PlatformView

@interface MobAdBannerPlatformView()<FlutterStreamHandler, BUNativeExpressBannerViewDelegate>
@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, strong) BUNativeExpressBannerView *bannerAd;
@property (nonatomic, strong) FlutterResult bannerCallback;

@end

@implementation MobAdBannerPlatformView
- (instancetype)initWithIdentifier:(int64_t)viewId
                    arguments:(id _Nullable)args
                    registrar:(NSObject<FlutterPluginRegistrar> *)registrar
{
    if (self = [super init]) {
        
        // 获取参数
        NSString *unitId;
        CGFloat bannerWidth = 0, bannerHeight = 0;
        if ([args isKindOfClass:[NSDictionary class]]) {
            unitId = args[@"unitId"];
            bannerWidth = [args[@"width"] floatValue];
            bannerHeight = [args[@"height"] floatValue];
        }
        
        if (bannerWidth <= 0.0) {
            bannerWidth = [UIScreen mainScreen].bounds.size.width;
            bannerHeight = bannerWidth /6.4;
        }
        
        // 加载banner
        self.bannerAd = [[BUNativeExpressBannerView alloc] initWithSlotID:unitId rootViewController:[KawaAdPlugin findCurrentShowingViewController] adSize:CGSizeMake(bannerWidth, bannerHeight)];
        self.bannerAd.frame = CGRectMake(0, 0, bannerWidth, bannerHeight);
        _bannerAd.delegate = self;
        // 容器view
        NSLog(@"%f--%f",bannerWidth,bannerHeight);
        _containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, bannerWidth, bannerHeight)];
        _containerView.backgroundColor = [UIColor clearColor];
        [self.bannerAd loadAdData];
        
        // 事件通道
        NSString *channelName = [NSString stringWithFormat:@"com.mob.adsdk/banner_event_%lld", viewId];
        FlutterEventChannel *eventChannel = [FlutterEventChannel eventChannelWithName:channelName binaryMessenger:[registrar messenger]];
        [eventChannel setStreamHandler:self];
    }
    return self;
}

- (void)dealloc {
    NSLog(@"%s", __func__);
}

- (nonnull UIView *)view {
    return _containerView;
}

- (FlutterError* _Nullable)onListenWithArguments:(NSString *_Nullable)arguments
                                       eventSink:(FlutterEventSink)events {
    NSLog(@"banner event -> listen");
    if (events) {
        self.bannerCallback = events;
    }
    return nil;
}

- (FlutterError *)onCancelWithArguments:(id)arguments {
    NSLog(@"banner event -> cancel listen");
    return nil;
}

#pragma mark - BannerAdDelegate
/**
 This method is called when bannerAdView ad slot loaded successfully.
 @param bannerAdView : view for bannerAdView
 */
- (void)nativeExpressBannerAdViewDidLoad:(BUNativeExpressBannerView *)bannerAdView{
    if (self.bannerCallback) {
        self.bannerCallback(@{@"event":@"onAdLoad"});
    }
}

/**
 This method is called when bannerAdView ad slot failed to load.
 @param error : the reason of error
 */
- (void)nativeExpressBannerAdView:(BUNativeExpressBannerView *)bannerAdView didLoadFailWithError:(NSError *_Nullable)error{
    if (self.bannerCallback) {
        self.bannerCallback(@{@"event":@"onAdError",@"error":error.localizedDescription,@"code":@(error.code)});
        self.bannerCallback = nil;
    }
}

- (void)nativeExpressBannerAdViewRenderSuccess:(BUNativeExpressBannerView *)bannerAdView{
    [_containerView addSubview:bannerAdView];
}
/**
 This method is called when a nativeExpressAdView failed to render.
 @param error : the reason of error
 */
- (void)nativeExpressBannerAdViewRenderFail:(BUNativeExpressBannerView *)bannerAdView error:(NSError * __nullable)error{
    if (self.bannerCallback) {
        self.bannerCallback(@{@"event":@"onAdError",@"error":error.localizedDescription,@"code":@(error.code)});
        self.bannerCallback = nil;
    }
}

/**
 This method is called when bannerAdView ad slot showed new ad.
 */
- (void)nativeExpressBannerAdViewWillBecomVisible:(BUNativeExpressBannerView *)bannerAdView{
    if (self.bannerCallback) {
        self.bannerCallback(@{@"event":@"onAdShow"});
    }
}

/**
 This method is called when bannerAdView is clicked.
 */
- (void)nativeExpressBannerAdViewDidClick:(BUNativeExpressBannerView *)bannerAdView{
    if (self.bannerCallback) {
        self.bannerCallback(@{@"event":@"onAdClick"});
    }
}
/**
 This method is called when another controller has been closed.
 @param interactionType : open appstore in app or open the webpage or view video ad details page.
 */
- (void)nativeExpressBannerAdViewDidCloseOtherController:(BUNativeExpressBannerView *)bannerAdView interactionType:(BUInteractionType)interactionType{
    if (self.bannerCallback) {
        self.bannerCallback(@{@"event":@"onAdAlertClose"});
    }
}

- (void)nativeExpressBannerAdView:(BUNativeExpressBannerView *)bannerAdView dislikeWithReason:(NSArray<BUDislikeWords *> *)filterwords{
    if (self.bannerCallback) {
        self.bannerCallback(@{@"event":@"onAdClose"});
        [self.bannerAd removeFromSuperview];
    }
}

/**
 This method is called when the Ad view container is forced to be removed.
 @param bannerAdView : Express Banner Ad view container
 */
- (void)nativeExpressBannerAdViewDidRemoved:(BUNativeExpressBannerView *)bannerAdView{
    if (self.bannerCallback) {
        self.bannerCallback(@{@"event":@"onAdClose"});
        [self.bannerAd removeFromSuperview];
    }
}

@end

#pragma mark - PlatformViewFactory

@interface MobAdBannerPlatformViewFactory()
@property (nonatomic, strong) NSObject<FlutterPluginRegistrar> *registrar;
@end

@implementation MobAdBannerPlatformViewFactory

- (instancetype)initWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
    self = [super init];
    if (self) {
        _registrar = registrar;
    }
    return self;
}

- (NSObject<FlutterMessageCodec>*)createArgsCodec {
    return [FlutterStandardMessageCodec sharedInstance];
}

- (NSObject<FlutterPlatformView> *)createWithFrame:(CGRect)frame viewIdentifier:(int64_t)viewId arguments:(id)args {
    return [[MobAdBannerPlatformView alloc] initWithIdentifier:viewId arguments:args registrar:_registrar];
}

@end
